package com.cysion.study.widget.downmenu

import android.animation.ObjectAnimator
import android.content.Context
import android.graphics.Canvas
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.PopupWindow
import com.cysion.study.R
import com.cysion.study.entity.Child
import kotlinx.android.synthetic.main.down_menu_title.view.*
import kotlinx.android.synthetic.main.popup_menu.view.*

/**
 * Created by chu on 2019-07-14.
 */
class SimpleDropDownMenu1(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0,
    defStyleRes: Int = 0
) :
    LinearLayout(context, attrs, defStyleAttr, defStyleRes),
    SimpleDropDownMenuAdapter1.ItemClickListener, ChildMenuAdapter.ItemClickListener {
    private var mMenuItemList = mutableListOf<MenuItem1>()
    private var mMenuItemAdapter: SimpleDropDownMenuAdapter1? = null
    private var mMenuOpenState = false
    var dropDownMenuOpenStateListener: OnDropDownMenuOpenStateListener? = null
    var menuItemClickListener: OnMenuItemClickListener? = null
    var clickItemCloseMenu = true

    //    private var mTitleItem: MenuItem1? = null
    private lateinit var mRootView: View

    //弹出窗窗口
    private var mPopupWindow: PopupWindow? = null
    //阴影(PopupWindow 使用卡片式布局无法设置阴影? 采用其他的阴影添加方式)
//    private var mShadow: CrazyShadow? = null


    interface OnDropDownMenuOpenStateListener {
        fun dropDownMenuStateChanges(menuOpenState: Boolean)
    }

    interface OnMenuItemClickListener {
        fun onMenuItemClickListener(v: View, position: Int)
        fun onMenuClick(name: String, ids: String)
    }

    constructor(mContext: Context, mAttrs: AttributeSet?) : this(
        context = mContext,
        attrs = mAttrs
    ) {
        initView()
    }

    private fun initView() {
        mRootView = LayoutInflater.from(context).inflate(R.layout.down_menu_title, this)
        initPopWindows()
        mRootView.setOnClickListener {
            if (mMenuOpenState) {
                closeMenu()
            } else {
                openMenu()
            }
        }
    }

    //子列表
    var childList = mutableListOf<Child>()
    var childAdapter: ChildMenuAdapter? = null

    private fun initPopWindows() {
        val popWindows = LayoutInflater.from(context).inflate(R.layout.popup_menu, null)
        mPopupWindow =
            PopupWindow(popWindows, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, true)
        mPopupWindow?.animationStyle = R.style.MyPopupWindow_anim_style
        mPopupWindow?.setOnDismissListener {
            closeMenu()
        }

        mMenuItemAdapter = SimpleDropDownMenuAdapter1(this.context, mMenuItemList)
        mMenuItemAdapter?.itemClickListener = this
        (popWindows.menu_item_list as RecyclerView).layoutManager =
            LinearLayoutManager(this.context, LinearLayoutManager.VERTICAL, false)
        (popWindows.menu_item_list as RecyclerView).adapter = mMenuItemAdapter

        childAdapter = ChildMenuAdapter(childList)
        childAdapter?.itemClickListener = this
        (popWindows.child_item_list as RecyclerView).layoutManager =
            LinearLayoutManager(this.context, LinearLayoutManager.VERTICAL, false)
        (popWindows.child_item_list as RecyclerView).adapter = childAdapter
    }

    public fun openMenu() {
        menuOpenStateChange(true)
        startOpenMenuAnimator()
        mPopupWindow?.showAsDropDown(mRootView, 0, 0)
        showShadow()
    }


    private fun showShadow() {
        /* mShadow = CrazyShadow.Builder()
             .setContext(context)
             .setDirection(CrazyShadowDirection.ALL)
             .setShadowRadius(5f)
             .setCorner(10f)
             .setImpl(CrazyShadow.IMPL_WRAP)
             .action(mPopupWindow?.contentView?.popup_menu_linear)*/
    }

    private fun removeShadow() {
//        mShadow?.remove()
    }

    public fun closeMenu() {
        var names = StringBuilder()
        var ids = StringBuilder()
        //isShowChild =true  处理一级点击返回
        if (clickItemCloseMenu) {
            for (obj in mMenuItemList) {
                if (obj.isCheck) {
                    names.append("," + obj.itemTitle)
                    ids.append("," + obj.itemId)
                }
            }
        } else {
            /*for (obj in childList) {
                if (obj.isCheck) {
                    names.append("," + obj.name)
                    ids.append("," + obj.id)
                }
            }*/
            for (obj in mMenuItemList) {
                for (item in obj.child) {
                    if (item.isCheck) {
                        names.append("," + item.name)
                        ids.append("," + item.id)
                        println("###遍历科目=" + names + ids)
                    }
                }
            }
        }

        if (names.length > 0) {
            names.deleteCharAt(0)
        }
        if (ids.length > 0) {
            ids.deleteCharAt(0)
        }
        menuItemClickListener?.onMenuClick(names.toString(), ids.toString())
        menuOpenStateChange(false)
        startCloseMenuAnimator()
        mPopupWindow?.dismiss()
        removeShadow()
    }

    private fun menuOpenStateChange(state: Boolean) {
        mMenuOpenState = state
        dropDownMenuOpenStateListener?.dropDownMenuStateChanges(mMenuOpenState)
    }

    private fun startOpenMenuAnimator() {
        val oa = ObjectAnimator.ofFloat(
            mRootView.menu_img_up_down,
            "rotation", 0f, -230f, -180f
        )
        oa.duration = 300
        oa.start()
    }

    private fun startCloseMenuAnimator() {
        val oa = ObjectAnimator.ofFloat(
            mRootView.menu_img_up_down,
            "rotation", -180f, 50f, 0f
        )
        oa.duration = 300
        oa.start()
    }

    fun addMenuItem(menuItemList: MutableList<MenuItem1>, titleItem: Int = 0) {
        this.mMenuItemList.clear()
        this.mMenuItemList.addAll(menuItemList)
        // 如果默认列表第一项
        setTitleItem(menuItemList[titleItem])
        mMenuItemList.remove(menuItemList[titleItem])
        this.mMenuItemAdapter?.notifyDataSetChanged()
    }

    //添加数据源
    fun addMenuItemForTitle(menuItemList: MutableList<MenuItem1>, titleItem: MenuItem1) {
        this.mMenuItemList.clear()
        this.mMenuItemList.addAll(menuItemList)

        setTitleItem(titleItem)
//        mMenuItemList.remove(menuItemList[titleItem])
        this.mMenuItemAdapter?.notifyDataSetChanged()
    }


    //添加子数据源
    fun addMenuItemForChild(menuItemList: MutableList<MenuItem1>, titleItem: MenuItem1) {
        this.mMenuItemList.clear()
        this.mMenuItemList.addAll(menuItemList)

        setTitleItem(titleItem)
//        mMenuItemList.remove(menuItemList[titleItem])
        this.mMenuItemAdapter?.notifyDataSetChanged()
    }

    // 设置标题项
    fun setTitleItem(titleItem: MenuItem1) {
//        this.mTitleItem = titleItem
        mRootView.down_menu_title_item.text = titleItem.itemTitle
//        mRootView.menu_title_img_icon.resources = titleItem.itemIcon

    }

    //设置选择菜单图标
    fun showImgIcon(b: Boolean) {
        if (b) {
            mRootView.menu_title_img_icon.visibility = View.VISIBLE
        } else {
            mRootView.menu_title_img_icon.visibility = View.GONE
//            mMenuItemAdapter?.showImg(b)
        }
    }

    //    private var isShowChild = false
    //设置选择菜单图标
    fun ShowOneIcon(b: Boolean) {
//        this.isShowChild = b
//        mMenuItemAdapter?.showChildList(b, titleItem.child)
        mMenuItemAdapter?.showOneIcon(b)
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        if (mMenuOpenState) {
            mPopupWindow?.isTouchable = true
            mPopupWindow?.isOutsideTouchable = true
        }
    }


    var checkClickListener: CheckClickListener? = null

    interface CheckClickListener {
        fun onItemCheck(v: View, position: Int)
    }


    //下拉条目选择事件
    override fun onItemClick(v: View, position: Int) {

        if (clickItemCloseMenu) {//一级下拉点击事件  否的话处理子列表
//            closeMenu()//关闭下拉框
//            menuItemClickListener?.onMenuItemClickListener(v, position)//点击下拉一级条目立马返回
            //处理下拉一级列表选中状态
            for (obj in mMenuItemList) {
                if (obj.itemId == mMenuItemList[position].itemId) {
                    obj.isCheck = !mMenuItemList[position].isCheck
                }
            }
//            mMenuItemAdapter?.showImg(true,position)//显示一级选中背景效果
            mMenuItemAdapter?.notifyDataSetChanged()
//            checkClickListener?.onItemCheck(v,position)
            closeItemCheckMenu()
        } else {
            for (obj in mMenuItemList) {
                if (obj.itemId == mMenuItemList[position].itemId) {
                    obj.isCheck = !mMenuItemList[position].isCheck
                }
            }
            mMenuItemAdapter?.showImg(true, position)//。显示一级选中背景效果
            mMenuItemAdapter?.notifyDataSetChanged()
            childList.clear()
            childList.addAll(mMenuItemList[position].child)
            childAdapter?.notifyDataSetChanged()
        }

    }

    //子列表点击
    override fun onChildItemClick(v: View, position: Int) {
        for (obj in childList) {
//            obj.isCheck = obj.id == childList[position].id//列表单选
            if (obj.id == childList[position].id) {
                obj.isCheck = !childList[position].isCheck
            }
        }
        childAdapter?.notifyDataSetChanged()
        closeItemCheckMenu()
    }




    //处理多选结果同步显示到选择框中
    public fun closeItemCheckMenu() {
         var names = StringBuilder()
         var ids = StringBuilder()
        //isShowChild =true  处理一级点击返回
        if (clickItemCloseMenu) {
            for (obj in mMenuItemList) {
                if (obj.isCheck) {
                    names.append("," + obj.itemTitle)
                    ids.append("," + obj.itemId)
                }
            }
        } else {
            for (obj in mMenuItemList) {
                for (item in obj.child) {
                    if (item.isCheck) {
                        names.append("," + item.name)
                        ids.append("," + item.id)
                        println("###遍历科目=" + names + ids)
                    }
                }
            }

            /*for (obj in childList) {
                if (obj.isCheck) {
                    names.append("," + obj.name)
                    ids.append("," + obj.id)
                    println("###遍历科目=" + names + ids)
                }
            }*/
        }

        if (names.length > 0) {
            names.deleteCharAt(0)
        }
        if (ids.length > 0) {
            ids.deleteCharAt(0)
        }
        menuItemClickListener?.onMenuClick(names.toString(), ids.toString())
    }

}
